const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const router = express.Router();

// 创建一个简单的存储机制来保存图片元数据
// 在实际应用中，您应该使用数据库来存储这些信息
const metadataFilePath = path.join(__dirname, '../uploads/metadata.json');

// 初始化元数据存储
let imageMetadata = {};
try {
  if (fs.existsSync(metadataFilePath)) {
    const data = fs.readFileSync(metadataFilePath, 'utf8');
    const parsedData = JSON.parse(data);
    
    // 检查是否是新的 {images: [...]} 格式
    if (parsedData.images && Array.isArray(parsedData.images)) {
      console.log('Converting new format metadata to old format');
      // 转换为旧格式 {filename: metadata}
      imageMetadata = {};
      parsedData.images.forEach(img => {
        if (img.filename) {
          imageMetadata[img.filename] = img;
        }
      });
    } else {
      // 使用旧格式
      imageMetadata = parsedData;
    }
    console.log('Loaded image metadata from file');
  } else {
    console.log('No metadata file found, creating a new one');
    // 确保uploads目录存在
    if (!fs.existsSync(path.join(__dirname, '../uploads'))) {
      fs.mkdirSync(path.join(__dirname, '../uploads'), { recursive: true });
    }
    // 创建空的元数据文件
    imageMetadata = {};
    fs.writeFileSync(metadataFilePath, JSON.stringify({images: []}), 'utf8');
  }
} catch (err) {
  console.error('Error loading metadata:', err);
  // 如果无法加载元数据，使用空对象
  imageMetadata = {};
}

// 保存元数据到文件
function saveMetadata() {
  try {
    // 转换为新格式 {images: [...]} 来保存
    const metadataToSave = {
      images: Object.values(imageMetadata)
    };
    fs.writeFileSync(metadataFilePath, JSON.stringify(metadataToSave, null, 2), 'utf8');
    console.log('Saved image metadata to file');
  } catch (err) {
    console.error('Error saving metadata:', err);
  }
}

// 1. CREATE UPLOADS FOLDER IF MISSING
const uploadDir = path.join(__dirname, '../uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
  console.log('Created uploads directory');
}

// 2. CONFIGURE FILE UPLOAD
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const uniqueName = Date.now() + '-' + Math.round(Math.random() * 1E9) + path.extname(file.originalname);
    cb(null, uniqueName);
  }
});

const upload = multer({ storage });

// 3. UPLOAD ENDPOINT
// In routes/upload.js - REPLACE the entire router.post('/') handler
router.post('/', (req, res, next) => {
  console.log('Upload request headers:', req.headers);
  console.log('Upload request body:', req.body);
  upload.single('image')(req, res, (err) => {
    if (err) {
      console.error('Multer error:', err);
      return res.status(400).json({ error: err.message });
    }
    
    try {
      console.log('Upload request received');
      console.log('Files:', req.file);
      console.log('Body:', req.body);

      if (!req.file) {
        console.error('No file uploaded');
        return res.status(400).json({ error: 'No file received' });
      }

      // 保存图片元数据
      const { collection, description } = req.body;
      imageMetadata[req.file.filename] = {
        filename: req.file.filename,
        originalname: req.file.originalname,
        collection: collection || 'paperwork', // 默认为paperwork
        description: description || 'No description provided',
        uploadDate: new Date().toISOString()
      };
      
      // 保存元数据到文件
      saveMetadata();

      res.json({
        success: true,
        filename: req.file.filename,
        path: `/uploads/${req.file.filename}`
      });

    } catch (err) {
      console.error('SERVER ERROR:', err);
      res.status(500).json({ error: err.message });
    }
  });
});

// 添加获取所有上传图片的API端点
router.get('/', (req, res) => {
  try {
    console.log('GET /api/uploads request received');
    console.log('Current imageMetadata keys:', Object.keys(imageMetadata));
    
    // 读取uploads目录中的所有文件
    fs.readdir(uploadDir, (err, files) => {
      if (err) {
        console.error('Error reading uploads directory:', err);
        return res.status(500).json({ error: 'Failed to read uploads directory' });
      }
      
      // 过滤出图片文件 (排除metadata.json等文件)
      const imageFiles = files.filter(file => {
        return /\.(jpg|jpeg|png|gif)$/i.test(file) && !file.includes('metadata');
      });
      
      console.log('Found image files:', imageFiles.length);
      
      // 构建包含元数据的图片列表
      const images = imageFiles.map(filename => {
        // 获取该文件的元数据，如果没有则使用默认值
        const metadata = imageMetadata[filename];
        
        if (metadata) {
          console.log(`Found metadata for ${filename}:`, metadata.collection);
          return {
            filename: metadata.filename || filename,
            collection: metadata.collection || 'paperwork',
            description: metadata.description || 'No description available',
            originalname: metadata.originalname,
            uploadDate: metadata.uploadDate
          };
        } else {
          console.log(`No metadata found for ${filename}, using defaults`);
          return {
            filename,
            collection: 'paperwork', // 默认分类
            description: 'No description available' // 默认描述
          };
        }
      });
      
      console.log('Returning', images.length, 'images');
      res.json({
        success: true,
        images: images
      });
    });
  } catch (err) {
    console.error('SERVER ERROR:', err);
    res.status(500).json({ error: err.message });
  }
});

// 导出路由器
module.exports = router;